package com.smartcampusbackend.controller;

import com.smartcampusbackend.model.Announcement;
import com.smartcampusbackend.model.AnnouncementAttachment;
import com.smartcampusbackend.service.AnnouncementService;
import com.smartcampusbackend.service.UserReadStatusService;
import com.smartcampusbackend.service.AnnouncementAttachmentService;
import com.smartcampusbackend.util.FileUploadUtil;
import com.smartcampusbackend.service.ActivitySignupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/api/announcement")
@CrossOrigin(origins = "*")
public class AnnouncementController {
    @Autowired
    private AnnouncementService announcementService;
    
    @Autowired
    private UserReadStatusService userReadStatusService;

    @Autowired
    private AnnouncementAttachmentService announcementAttachmentService;

    @Autowired
    private ActivitySignupService activitySignupService;

    //发布公告（三种）
    @PostMapping
    public Map<String, Object> publish(@RequestBody Announcement announcement) {
        announcement.setPublishTime(new Date());
        int result = announcementService.publishAnnouncement(announcement);
        Map<String, Object> resp = new HashMap<>();
        resp.put("code", result > 0 ? 200 : 500);
        resp.put("message", result > 0 ? "发布成功" : "发布失败");
        return resp;
    }

    //获取公告列表
    @GetMapping
    public Map<String, Object> list(@RequestParam(required = false) String type,
                                    @RequestParam(required = false) String publisher,
                                    @RequestParam(required = false) Integer userId,
                                    @RequestParam(required = false) String keyword,
                                    @RequestParam(required = false, defaultValue = "1") Integer page,
                                    @RequestParam(required = false, defaultValue = "10") Integer size) {
        Map<String, Object> resp = new HashMap<>();
        
        if (userId != null && (type == null || "all".equals(type) || "NEWS".equals(type) || "NOTICE".equals(type) || "ACTIVITY".equals(type))) {
            // 返回带阅读状态的列表
            List<Map<String, Object>> list = announcementService.getAnnouncementsWithReadStatus(type, publisher, userId, keyword, page, size);
            resp.put("code", 200);
            resp.put("data", list);
            resp.put("total", announcementService.getAnnouncementsCount(type, publisher, keyword));
        } else {
            // 返回普通列表
            List<Announcement> list = announcementService.getAnnouncements(type, publisher, keyword, page, size);
            resp.put("code", 200);
            resp.put("data", list);
            resp.put("total", announcementService.getAnnouncementsCount(type, publisher, keyword));
        }
        
        return resp;
    }

    //获取公告的详情
    @GetMapping("/{id}")
    public Map<String, Object> detail(@PathVariable Integer id, 
                                     @RequestParam(required = false) Integer userId) {
        Map<String, Object> resp = new HashMap<>();
        Announcement ann = (userId != null)
            ? announcementService.getAnnouncementWithReadStatus(id, userId)
            : announcementService.getAnnouncementById(id);
        if (ann != null) {
            Map<String, Object> data = new HashMap<>();
            // 手动put所有字段，保证兼容性
            data.put("id", ann.getId());
            data.put("type", ann.getType());
            data.put("title", ann.getTitle());
            data.put("content", ann.getContent());
            data.put("attachment", ann.getAttachment());
            data.put("publisher", ann.getPublisher());
            data.put("publishTime", ann.getPublishTime());
            data.put("location", ann.getLocation());
            data.put("remark", ann.getRemark());
            data.put("images", ann.getImages());
            data.put("layout", ann.getLayout());
            data.put("activityLimit", ann.getActivityLimit());
            data.put("signupUrl", ann.getSignupUrl());
            data.put("signupDeadline", ann.getSignupDeadline());
            data.put("status", ann.getStatus());
            data.put("isDraft", ann.getIsDraft());
            data.put("draftTime", ann.getDraftTime());
            data.put("attachments", ann.getAttachments());
            // 若为活动类型，补充approvedCount
            if ("ACTIVITY".equals(ann.getType())) {
                int approvedCount = activitySignupService.getApprovedSignupCount(ann.getId());
                data.put("approvedCount", approvedCount);
            }
            resp.put("code", 200);
            resp.put("data", data);
        } else {
            resp.put("code", 404);
            resp.put("data", null);
        }
        return resp;
    }

    //我发布的
    @GetMapping("/my")
    public Map<String, Object> my(@RequestParam String publisher, 
                                 @RequestParam(required = false) String type,
                                 @RequestParam(required = false) Integer userId) {
        Map<String, Object> resp = new HashMap<>();
        
        if (userId != null && (type == null || "NEWS".equals(type) || "NOTICE".equals(type) || "ACTIVITY".equals(type))) {
            // 返回带阅读状态的列表
            List<Map<String, Object>> list = announcementService.getAnnouncementsWithReadStatus(type, publisher, userId);
            resp.put("code", 200);
            resp.put("data", list);
        } else {
            // 返回普通列表
            List<Announcement> list = announcementService.getAnnouncements(type, publisher);
            resp.put("code", 200);
            resp.put("data", list);
        }
        
        return resp;
    }
    
    //删除公告
    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable Integer id, 
                                     @RequestParam String publisher) {
        Map<String, Object> resp = new HashMap<>();
        try {
            int result = announcementService.deleteAnnouncement(id, publisher);
            resp.put("code", result > 0 ? 200 : 500);
            resp.put("message", result > 0 ? "删除成功" : "删除失败");
        } catch (RuntimeException e) {
            resp.put("code", 400);
            resp.put("message", e.getMessage());
        }
        return resp;
    }

    
    // 草稿相关接口
    
    //保存草稿
    @PostMapping("/draft")
    public Map<String, Object> saveDraft(@RequestBody Announcement announcement) {
        Map<String, Object> resp = new HashMap<>();
        try {
            int result = announcementService.saveDraft(announcement);
            resp.put("code", result > 0 ? 200 : 500);
            resp.put("message", result > 0 ? "草稿保存成功" : "草稿保存失败");
        } catch (RuntimeException e) {
            resp.put("code", 400);
            resp.put("message", e.getMessage());
        }
        return resp;
    }
    
    //更新草稿
    @PutMapping("/draft")
    public Map<String, Object> updateDraft(@RequestBody Announcement announcement) {
        Map<String, Object> resp = new HashMap<>();
        try {
            int result = announcementService.updateDraft(announcement);
            resp.put("code", result > 0 ? 200 : 500);
            resp.put("message", result > 0 ? "草稿更新成功" : "草稿更新失败");
        } catch (RuntimeException e) {
            resp.put("code", 400);
            resp.put("message", e.getMessage());
        }
        return resp;
    }
    
    //获取草稿列表
    @GetMapping("/draft")
    public Map<String, Object> getDrafts(@RequestParam String publisher,
                                        @RequestParam(required = false) String type) {
        List<Announcement> drafts = announcementService.getDrafts(publisher, type);
        Map<String, Object> resp = new HashMap<>();
        resp.put("code", 200);
        resp.put("data", drafts);
        return resp;
    }
    
    //发布草稿
    @PostMapping("/draft/{id}/publish")
    public Map<String, Object> publishDraft(@PathVariable Integer id,
                                           @RequestParam String publisher) {
        Map<String, Object> resp = new HashMap<>();
        try {
            int result = announcementService.publishDraft(id, publisher);
            resp.put("code", result > 0 ? 200 : 500);
            resp.put("message", result > 0 ? "草稿发布成功" : "草稿发布失败");
        } catch (RuntimeException e) {
            resp.put("code", 400);
            resp.put("message", e.getMessage());
        }
        return resp;
    }
    
    //删除草稿
    @DeleteMapping("/draft/{id}")
    public Map<String, Object> deleteDraft(@PathVariable Integer id,
                                          @RequestParam String publisher) {
        Map<String, Object> resp = new HashMap<>();
        try {
            int result = announcementService.deleteDraft(id, publisher);
            resp.put("code", result > 0 ? 200 : 500);
            resp.put("message", result > 0 ? "草稿删除成功" : "草稿删除失败");
        } catch (RuntimeException e) {
            resp.put("code", 400);
            resp.put("message", e.getMessage());
        }
        return resp;
    }

    // 附件相关接口
    
    /**
     * 上传附件
     */
    @PostMapping("/attachment/upload")
    public Map<String, Object> uploadAttachment(@RequestParam("file") MultipartFile file, 
                                               HttpServletRequest request) {
        Map<String, Object> resp = new HashMap<>();
        try {
            String fileUrl = FileUploadUtil.uploadAttachment(file);
            String fileName = file.getOriginalFilename();
            
            resp.put("code", 200);
            resp.put("message", "上传成功");
            resp.put("data", Map.of(
                "name", fileName,
                "url", fileUrl,
                "size", file.getSize(),
                "type", file.getContentType()
            ));
        } catch (Exception e) {
            resp.put("code", 500);
            resp.put("message", "上传失败: " + e.getMessage());
        }
        return resp;
    }
    
    // 图片上传
    @PostMapping("/image/upload")
    public Map<String, Object> uploadImage(@RequestParam("file") MultipartFile file, 
                                          HttpServletRequest request) {
        Map<String, Object> resp = new HashMap<>();
        try {
            String imageUrl = FileUploadUtil.uploadImage(file, "images");
            String fileName = file.getOriginalFilename();
            
            resp.put("code", 200);
            resp.put("message", "上传成功");
            resp.put("data", Map.of(
                "name", fileName,
                "url", imageUrl,
                "size", file.getSize(),
                "type", file.getContentType()
            ));
        } catch (Exception e) {
            resp.put("code", 500);
            resp.put("message", "上传失败: " + e.getMessage());
        }
        return resp;
    }

    /**
     * 获取公告的附件列表
     */
    @GetMapping("/{id}/attachments")
    public Map<String, Object> getAttachments(@PathVariable Integer id) {
        Map<String, Object> resp = new HashMap<>();
        try {
            List<AnnouncementAttachment> attachments = announcementAttachmentService.getAttachmentsByAnnouncementId(id);
            resp.put("code", 200);
            resp.put("message", "获取附件列表成功");
            resp.put("data", attachments);
        } catch (Exception e) {
            resp.put("code", 500);
            resp.put("message", "获取附件列表失败: " + e.getMessage());
            resp.put("data", null);
        }
        return resp;
    }
    
    /**
     * 访问附件文件
     */
    @GetMapping("/attachment/{fileName}")
    public ResponseEntity<Resource> getAttachment(@PathVariable String fileName) {
        try {
            Path filePath = Paths.get("uploads/attachments/" + fileName);
            Resource resource = new org.springframework.core.io.FileSystemResource(filePath.toFile());
            
            if (resource.exists()) {
                return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                    .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    /**
     * 访问图片文件
     */
    @GetMapping("/image/{fileName}")
    public ResponseEntity<Resource> getImage(@PathVariable String fileName) {
        try {
            Path filePath = Paths.get("uploads/images/" + fileName);
            Resource resource = new org.springframework.core.io.FileSystemResource(filePath.toFile());
            
            if (resource.exists()) {
                return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, "image/*")
                    .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
} 